package map;

import net.ChatClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class MapChatClient02 {

    private static Socket socket;


    public MapChatClient02() {
        try {
            socket = new Socket("127.0.0.1", 8080);
        } catch (IOException e) {
            System.out.println("连接失败");
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void start() {
        Scanner sc = null;
        PrintWriter pw = null;
        BufferedReader br = null;
        try {
            pw = new PrintWriter(socket.getOutputStream(), true);

            sc = new Scanner(System.in);
            while (true) {
                System.out.println("请输入用户昵称");
                String userName = sc.nextLine();
                if (userName.trim().isEmpty()) {
                    System.out.println("昵称不能为空");
                    continue;
                }
                pw.println(userName);
                break;
            }

            new Thread(new MapChatClient02.ServerHandler()).start();

            System.out.print("发送内容：");
            while (true) {
                String chat = sc.nextLine();
                System.out.println();
                if ("exit".equalsIgnoreCase(chat)) {
                    System.out.println("聊天结束，关闭聊天室!");
                    break;
                }
                pw.println(chat);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            sc.close();
            if (pw != null) pw.close();

            if (socket != null) try {
                socket.close();
                System.out.println("客户端退出");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private class ServerHandler implements Runnable {

        @Override
        public void run() {
            BufferedReader br = null;

            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
                String str;
                while (true) {
                    if ((str = br.readLine()) != null) {
                        System.out.println(str);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    public static void main(String[] args) {
        new MapChatClient().start();
    }


}
